import { apps } from "@/micro";
import { AppService } from "@/service/app-service";
import store from "./store";

class Shared {
  /**
   * 获取全部页面
   */
  public getAllPage(): Array<any> {
    const state = store.getState();
    return state.pages || [];
  }

  /**
   * 添加页面
   */
  public addPage(payload: any): void {
    const allPages = this.getAllPage();
    //基座应用判重
    if(!payload.microAppName){
      const activeIndex = allPages.findIndex((page:any) =>{
        return page.fullPath === payload.fullPath;
      })
      if(activeIndex !== -1){
        return;
      }
    }
    store.dispatch({
      type: "ADD_PAGE",
      payload
    });
  }

  /**
   * 更新页面
   * @param payload 
   */
  public updatePage(payload: any): void {
    const allPages = this.getAllPage();
    if (allPages && allPages.length > 0) {
      const index = allPages.findIndex((page: any) => {
        return page.microAppName + page.fullPath === payload.microAppName + payload.fullPath;
      });
      if (index > -1) {
        store.dispatch({
          type: "UPDATE_PAGE",
          payload: { index, data: payload }
        });
      }
    }
  }

  /**
   * 删除页面
   */
  public removePage(payload: any): void {
    const allPages = this.getAllPage();
    if (allPages && allPages.length > 0) {
      const index = allPages.findIndex((page: any) => {
        return page.microAppName + page.fullPath === payload.microAppName + payload.fullPath;
      });
      if (index > -1) {
        store.dispatch({
          type: "REMOVE_PAGE",
          payload: index
        });
      }
      if(payload.microAppName){
        AppService.getInstance().noticeMicroApp({ tag: payload.microAppName, action: 'REMOVE_PAGE', data: payload });
      }
    }
  }

  /**
   * 删除所有页面
   */
  public removeAllPage(): void {
    store.dispatch({
      type: "REMOVE_ALL"
    });
    AppService.getInstance().noticeAllMicroApp('REMOVE_ALL');
  }

  /**
   * 删除其他页面
   */
  public removeOther(payload: any): void {
    store.dispatch({
      type: "REMOVE_OTHER",
      payload
    });
    if (apps && apps.length > 0) {
      apps.forEach((app: any) => {
        if (Object.is(payload.microAppName, app.name)) {
          AppService.getInstance().noticeMicroApp({ tag: app.name, action: 'REMOVE_OTHER', data: payload });
        } else {
          AppService.getInstance().noticeMicroApp({ tag: app.name, action: 'REMOVE_ALL', data: payload });
        }
      })
    }
  }
}

const shared = new Shared();
export default shared;